import { Injectable, BadRequestException, Inject, forwardRef } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { WechatPayService } from './wechat-pay.service';
import { AlipayService } from './alipay.service';
import { Order } from '../orders/entities/order.entity';
import { CreatePaymentDto, PaymentMethod } from './dto/create-payment.dto';
import { OrdersService } from '../orders/orders.service';

@Injectable()
export class PaymentService {
  constructor(
    @InjectRepository(Order)
    private ordersRepository: Repository<Order>,
    private readonly wechatPayService: WechatPayService,
    private readonly alipayService: AlipayService,
    @Inject(forwardRef(() => OrdersService))
    private readonly ordersService: OrdersService,
  ) {}

  /**
   * 创建支付
   */
  async createPayment(createPaymentDto: CreatePaymentDto): Promise<any> {
    const { orderId, amount, paymentMethod, openid, returnUrl } =
      createPaymentDto;

    // 查询订单
    const order = await this.ordersRepository.findOne({
      where: { id: parseInt(orderId) },
    });

    if (!order) {
      throw new BadRequestException('订单不存在');
    }

    if (order.status !== 'pending') {
      throw new BadRequestException('订单状态不正确');
    }

    // 验证金额
    if (Math.abs(order.totalPrice - amount) > 0.01) {
      throw new BadRequestException('订单金额不匹配');
    }

    const outTradeNo = `${order.orderNo}`;
    const description = `DevTools Hub - ${order.planName}`;

    // 设置30分钟后过期
    const timeExpire = new Date(Date.now() + 30 * 60 * 1000);

    // 根据支付方式调用不同的支付接口
    switch (paymentMethod) {
      case PaymentMethod.WECHAT_NATIVE:
        const nativeResult = await this.wechatPayService.createNativePay({
          outTradeNo,
          totalAmount: amount,
          description,
          timeExpire,
        });
        return {
          paymentMethod: 'wechat_native',
          codeUrl: nativeResult.codeUrl,
          orderId: order.id,
          orderNo: order.orderNo,
        };

      case PaymentMethod.WECHAT_H5:
        const h5Result = await this.wechatPayService.createH5Pay({
          outTradeNo,
          totalAmount: amount,
          description,
          timeExpire,
          sceneInfo: {
            payer_client_ip: '127.0.0.1', // 应从请求中获取
            h5_info: {
              type: 'Wap',
            },
          },
        });
        return {
          paymentMethod: 'wechat_h5',
          h5Url: h5Result.h5Url,
          orderId: order.id,
          orderNo: order.orderNo,
        };

      case PaymentMethod.WECHAT_JSAPI:
        if (!openid) {
          throw new BadRequestException('JSAPI支付需要openid');
        }
        const jsapiResult = await this.wechatPayService.createJsapiPay({
          outTradeNo,
          totalAmount: amount,
          description,
          timeExpire,
          openid,
        });
        return {
          paymentMethod: 'wechat_jsapi',
          ...jsapiResult,
          orderId: order.id,
          orderNo: order.orderNo,
        };

      case PaymentMethod.ALIPAY_PAGE:
        const pagePayUrl = await this.alipayService.createPagePay({
          outTradeNo,
          totalAmount: amount,
          subject: description,
          body: `订单号: ${order.orderNo}`,
        });
        return {
          paymentMethod: 'alipay_page',
          payUrl: pagePayUrl,
          orderId: order.id,
          orderNo: order.orderNo,
        };

      case PaymentMethod.ALIPAY_WAP:
        const wapPayUrl = await this.alipayService.createWapPay({
          outTradeNo,
          totalAmount: amount,
          subject: description,
          body: `订单号: ${order.orderNo}`,
        });
        return {
          paymentMethod: 'alipay_wap',
          payUrl: wapPayUrl,
          orderId: order.id,
          orderNo: order.orderNo,
        };

      default:
        throw new BadRequestException('不支持的支付方式');
    }
  }

  /**
   * 查询支付状态
   * 
   * ⚠️ 重要：如果查到支付成功但订单未更新，自动触发订单更新
   */
  async queryPayment(orderNo: string, paymentMethod: string): Promise<any> {
    console.log('\n========== 🔍 查询支付状态 ==========');
    console.log('⏰ 时间:', new Date().toISOString());
    console.log('📦 订单号:', orderNo);
    console.log('💳 支付方式:', paymentMethod);

    try {
      // 先查询本地订单状态
      const order = await this.ordersRepository.findOne({
        where: { orderNo },
      });

      if (!order) {
        console.error('❌ 订单不存在');
        throw new BadRequestException('订单不存在');
      }

      console.log('📋 本地订单状态:', {
        订单状态: order.status,
        支付状态: order.paymentStatus,
        交易号: order.transactionId,
        支付时间: order.paidAt,
      });

      // 如果订单已经支付成功，直接返回
      if (order.status === 'paid' || order.status === 'completed') {
        console.log('✅ 订单已支付，直接返回成功');
        console.log('========== ✅ 查询完成 ==========\n');
        return {
          trade_state: 'SUCCESS',
          tradeStatus: 'TRADE_SUCCESS',
          out_trade_no: orderNo,
          transaction_id: order.transactionId,
        };
      }

      // 否则查询支付平台状态
      let result;
      if (paymentMethod.startsWith('wechat')) {
        console.log('🔄 查询微信支付平台...');
        result = await this.wechatPayService.queryOrder(orderNo);
      } else if (paymentMethod.startsWith('alipay')) {
        console.log('🔄 查询支付宝平台...');
        result = await this.alipayService.queryOrder(orderNo);
      } else {
        throw new BadRequestException('不支持的支付方式');
      }

      console.log('📱 支付平台返回:', result);

      // ✅ 关键修改：如果支付平台返回支付成功，但本地订单未更新，自动触发更新
      const isPaymentSuccess = result.trade_state === 'SUCCESS' || 
                               result.tradeStatus === 'TRADE_SUCCESS' ||
                               result.tradeStatus === 'TRADE_FINISHED';

      if (isPaymentSuccess && order.status === 'pending') {
        console.log('\x1b[33m⚠️ 发现支付成功但订单未更新，自动触发更新...\x1b[0m');
        
        // 提取支付信息
        const transactionId = result.transaction_id || result.trade_no || result.tradeNo;
        const paidAt = result.success_time 
          ? new Date(result.success_time) 
          : new Date();
        const totalAmount = result.amount?.total 
          ? result.amount.total / 100 
          : (result.total_amount ? parseFloat(result.total_amount) : order.totalPrice);

        console.log('💰 提取的支付信息:', {
          交易号: transactionId,
          支付时间: paidAt,
          支付金额: totalAmount,
        });

        try {
          await this.ordersService.handlePaymentSuccess({
            orderNo: orderNo,
            transactionId: transactionId,
            paymentMethod: paymentMethod.startsWith('wechat') ? 'wechat' : 'alipay',
            paidAt: paidAt,
            paidAmount: totalAmount,
          });

          console.log('\x1b[32m🎉 订单自动更新成功！\x1b[0m');
        } catch (updateError) {
          console.error('\x1b[31m❌ 自动更新订单失败:\x1b[0m', updateError);
          console.error(updateError.stack);
          // 不抛出错误，继续返回支付状态
        }
      }

      console.log('========== ✅ 查询完成 ==========\n');

      return result;
    } catch (error) {
      console.error('========== ❌ 查询失败 ==========');
      console.error('错误:', error.message);
      console.error('错误堆栈:', error.stack);
      throw error;
    }
  }
}




